package com.fh.shop.admin.biz.user;

import com.fh.shop.admin.common.DataTableResult;
import com.fh.shop.admin.common.ServerResponse;
import com.fh.shop.admin.mapper.user.IJobMapper;
import com.fh.shop.admin.mapper.user.IUserMapper;
import com.fh.shop.admin.param.user.UserAddParam;
import com.fh.shop.admin.param.user.UserQueryParam;
import com.fh.shop.admin.param.user.UserUpdateParam;
import com.fh.shop.admin.po.user.Job;
import com.fh.shop.admin.po.user.User;
import com.fh.shop.admin.vo.user.UserVo;
import com.fh.shop.admin.common.ResponseEnum;
import com.fh.shop.admin.param.user.UserPasswordParam;
import com.fh.shop.admin.po.user.UserItem;
import com.fh.shop.admin.util.Md5Util;
import com.fh.shop.admin.util.OSSUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("userService")
public class IUserServiceImpl implements IUserService {
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IJobMapper jobMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(IUserServiceImpl.class);

    /**
     * 增加
     * @param userAddParam
     * @return
     */
    @Override
    public ServerResponse addUser(UserAddParam userAddParam) {
        //类型转换
        User user = buildUser(userAddParam);
        //插入数据库
        userMapper.addUser(user);

        //如果jobList有值才到数据库添加job数据
        List<Job> jobList = userAddParam.getJobList();
        if (jobList.size()>0){
            jobList.forEach(x -> {
                x.setUserId(user.getId());
                jobMapper.addJob(x);
            });
        }

        //返回给前台一个状态码和内容
        return ServerResponse.success();
    }

    private User buildUser(UserAddParam userAddParam) {
        User user = new User();
        user.setUserName(userAddParam.getUserName());
        user.setBirthday(userAddParam.getBirthday());
        user.setHeadImagePath(userAddParam.getHeadImagePath());
        //新增密码时 加盐加密
        user.setUserPassword(Md5Util.md5(userAddParam.getUserPassword()));
        user.setSex(userAddParam.getSex());
        user.setRealName(userAddParam.getRealName());
        user.setShengId(userAddParam.getShengId());
        user.setShiId(userAddParam.getShiId());
        user.setXianId(userAddParam.getXianId());
        return user;
    }

    /**
     * 查询+条件
     * @param userQueryParam
     * @return
     */
    @Override
    public DataTableResult findList(UserQueryParam userQueryParam) {
        LOGGER.info("业务逻辑层——查询所有用户数据");
        //查询总条数
        Long count = userMapper.findCount(userQueryParam);
        //查询符合要求的数据
        List<UserItem> userList = userMapper.findUserList(userQueryParam);
        return new DataTableResult(userQueryParam.getDraw(),count,count,userList);
    }


    /**
     * 回显
     * @param id
     * @return
     */
    @Override
    public ServerResponse findUserById(Long id) {
        UserItem user = userMapper.findUserById(id);
        List<Job> jobList = jobMapper.findJob(id);
        UserVo userVo = new UserVo();
        userVo.setUserItem(user);
        userVo.setJobList(jobList);
        return ServerResponse.success(userVo);
    }

    /**
     * 修改
     * @param
     * @return
     */
    @Override
    public ServerResponse updateUser(UserUpdateParam userUpdateParam, String realPath) {
        //类型转换
        User user = buildUpdate(userUpdateParam);

        //判断用户是否上传新图片——>判断新图片的值是否为空
        if (StringUtils.isEmpty(userUpdateParam.getNewHeadImg())){
            //为空说明用户没有上传新图片——>把老图片赋给新图片
            user.setHeadImagePath(userUpdateParam.getHeadImagePath());
        }else {
            //不为空说明用户上传了新图片 ——>把新图片的路径赋给原来的老图片
            user.setHeadImagePath(userUpdateParam.getNewHeadImg());
            //把原来的老图片路径删除 ——>需要删除硬盘上的文件
            //获取根目录:realPath+文件名进行删除
            /*String path = realPath + userUpdateParam.getHeadImagePath();
            File file = new File(path);
            if (file.exists()){//如果有内容
                //那么执行删除操作
                file.delete();
            }*/
            OSSUtil.deleteFile(userUpdateParam.getHeadImagePath());
        }

        //先删除之前得工作经历
        jobMapper.deleteJob(user.getId());
        //添加新得工作经历
        List<Job> jobList = userUpdateParam.getJobList();
        if (jobList.size()>0){
            jobList.forEach(x -> {
                x.setUserId(userUpdateParam.getId());
                jobMapper.addJob(x);
            });
        }

        userMapper.updateUser(user);
        return ServerResponse.success();
    }

    private User buildUpdate(UserUpdateParam userUpdateParam) {
        User user = new User();
        user.setId(userUpdateParam.getId());
        user.setUserName(userUpdateParam.getUserName());
        user.setRealName(userUpdateParam.getRealName());
        user.setBirthday(userUpdateParam.getBirthday());
        user.setSex(userUpdateParam.getSex());
        user.setShengId(userUpdateParam.getShengId());
        user.setShiId(userUpdateParam.getShiId());
        user.setXianId(userUpdateParam.getXianId());
        return user;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public ServerResponse deleteUser(Long id,String realPath) {
        //删除本地硬盘上的图片
        //先获取文件名
        User user = userMapper.findUserById(id);
        //得到全路径(注意拼接顺序)
        /*String path = realPath + user.getHeadImagePath();
        File file = new File(path);
        if (file.exists()){
            file.delete();
        }*/
        OSSUtil.deleteFile(user.getHeadImagePath());
        userMapper.deleteUser(id);
        return ServerResponse.success();
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    public ServerResponse deleteBatch(String ids,String realPath) {
        //如果ids不为空才进行操作
        if (StringUtils.isNotEmpty(ids)){
            String[] idArr = ids.split(",");
            List<Long> idList = new ArrayList<>();

            for (String s : idArr) {
                idList.add(Long.parseLong(s));
            }

            //批量去数据库查询
            List<User> userList = userMapper.findBatch(idList);
            //遍历所有数据得到文件名去硬盘上删除图片
            List<String> imgPaths = userList.stream().map(x -> x.getHeadImagePath()).collect(Collectors.toList());
            OSSUtil.deleteBatchFile(imgPaths);
            /*for (User user : userList) {
                //得到全路径
                String path = realPath + user.getHeadImagePath();
                File file = new File(path);
                if (file.exists()){
                    file.delete();
                }
            }*/
            userMapper.deleteBatch(idList);
        }
        return ServerResponse.success();
    }

    /**
     * 根据用户名查询用户信息
     * @param userName
     */
    @Override
    public User findUserByUserName(String userName) {
        return userMapper.findUserByUserName(userName);
    }

    /**
     * 修改密码
     * @param userPasswordParam
     * @return
     */
    @Override
    public ServerResponse updatePwd(UserPasswordParam userPasswordParam) {
        String oldPwd = userPasswordParam.getOldPassword();//用户输入的原密码
        String newPwd = userPasswordParam.getNewPassword();//用户输入的新密码
        String confirmPwd = userPasswordParam.getConfirmPassword();//用户输入的确认密码
        User sessionUser = userPasswordParam.getUser();//session中的值存入了user中，所以可以直接获取到session的值
        String dbPassword = sessionUser.getUserPassword();//登录用户的原密码
        Long id = sessionUser.getId();//登录用户的id

        //非空验证
        if(StringUtils.isEmpty(oldPwd)
                || StringUtils.isEmpty(newPwd)
                || StringUtils.isEmpty(confirmPwd)){
            return ServerResponse.error(ResponseEnum.PASSWORD_IS_NULL);
        }

        //原密码输入是否正确
        // 将用户输入的原密码加密后和数据库的密码对比
        if (!Md5Util.md5(oldPwd).equals(dbPassword)){
            return ServerResponse.error(ResponseEnum.OLDPASSWORD_ERROR);
        }

        //新密码不能和旧密码一致
        if (newPwd.equals(oldPwd)){
            return ServerResponse.error(ResponseEnum.NEWPASSWORD_OLDPASSWORD_ERROR);
        }

        //确认密码需要和新密码一致
        if (!confirmPwd.equals(newPwd)){
            return ServerResponse.error(ResponseEnum.CONFIRMPSSWORD_NEWPASSWORD_EQUAL);
        }

        //满足条件后即可修改
        User user = new User();
        user.setId(id);
        user.setUserPassword(Md5Util.md5(newPwd));
        userMapper.updatePwd(user);
        return ServerResponse.success();
    }

    //导出word
    @Override
    public Map<String, Object> findUser(Long userId) {
        //查询用户信息
        Map<String, Object> res = new HashMap<>();
        UserItem user = userMapper.findUserById(userId);
        //查询工作经历
        List<Job> job = jobMapper.findJob(userId);
        res.put("user",user);
        res.put("jobList",job);
        return res;
    }


}
